package edu.ccut.saturn.basecomponent.database.facade;

import java.sql.Connection;

import edu.ccut.saturn.basecomponent.database.ISaturnSQL;
import edu.ccut.saturn.basecomponent.database.ISaturnSQLBuilder;
import edu.ccut.saturn.basecomponent.database.IUpdateSQLBuilder;
import edu.ccut.saturn.basecomponent.database.SaturnSQLBuilderFactory;
import edu.ccut.saturn.basecomponent.database.SaturnSQLHandler;
import edu.ccut.saturn.basecomponent.database.util.SaturnDataUtil;
import edu.ccut.saturn.component.IDataItem;
import edu.ccut.saturn.component.SaturnComponentException;
import edu.ccut.saturn.component.SaturnData;

public class UpdateByPrimaryKey {
	public int execute(SaturnData saturnData,String specialcolumn,Connection conn) throws Exception {
		String dbType = SaturnDataUtil.getStandardDBType(saturnData);
		ISaturnSQLBuilder builder = SaturnSQLBuilderFactory.getSaturnSQLBuilder(dbType);
		if(builder!=null){
			IDataItem item = SaturnDataUtil.getPKDataItem(saturnData);
			if (item == null) {
				throw new SaturnComponentException(
						"Can not find primaryKey in SaturnData name is" + saturnData.getSaturnDataInfo().getDataFullKey());
			}
			Object primaryKeyValue =  saturnData.get(item.getName());
			if (primaryKeyValue == null) {
				throw new SaturnComponentException(
						"PrimaryKeyValue can not be null !");
			}
			String condition = " WHERE " + item.getColumn() + " ='" + primaryKeyValue + "' ";
			IUpdateSQLBuilder sqlBuilder = builder.getUpdateSQLBuilder(getBuilderType(saturnData));
			ISaturnSQL saturnSQL = sqlBuilder.build(saturnData, condition,specialcolumn);
			int count = SaturnSQLHandler.executeUpdate(saturnSQL, conn);
			return count;
		}
		return 0;
	}
	private String getBuilderType(SaturnData saturnData) {
		// 如果有大数据
		if (SaturnDataUtil.hasLOB(saturnData)) {
			return ISaturnSQL.UPDATE_LOB_OPERATION;
		} else {
			return ISaturnSQL.UPDATE_OPERATION;
		}
	}

//	private boolean hasLOB(SaturnData saturnData) {
//		IDataInfo dataInfo = saturnData.getSaturnDataInfo();
//		for (String key : dataInfo.keySet()) {
//			IDataItem dataItem = dataInfo.getDataItem(key);
//			if (OracleAttribute.isLOB(dataItem.getType())) {
//				if (saturnData.get(key) != null) {
//					return true;
//				}
//			}
//		}
//		return false;
//	}
}
